var express = require('express');
var router = express.Router();
const orderModel = require('../../database/order');
const { usersModel } = require('../../database/user');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 大屏统计接口
router.get('/overview/stats', async (req, res) => {
  try {
    // 获取今天和本月的时间范围
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
    const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 1);

    // 今日订单数
    const orderCount = await orderModel.countDocuments({ date: { $gte: today, $lt: tomorrow } });
    // 本月销售额
    const salesAgg = await orderModel.aggregate([
      { $match: { date: { $gte: monthStart, $lt: monthEnd } } },
      { $group: { _id: null, total: { $sum: "$amount" } } }
    ]);
    const sales = salesAgg[0]?.total || 0;
    // 活跃用户
    const users = await usersModel.countDocuments({ lastLogin: { $gte: today, $lt: tomorrow } });
    // 转化率（mock，除非有业务逻辑）
    const conversion = (Math.random() * 40).toFixed(1) + '%';
    // 随机趋势
    function randTrend() {
      const up = Math.random() > 0.5;
      const percent = (Math.random() * 10).toFixed(1) + '%';
      return { trend: (up ? '+' : '-') + percent, trendUp: up };
    }
    const t1 = randTrend();
    const t2 = randTrend();
    const t3 = randTrend();
    const t4 = randTrend();
    res.json([
      { title: '今日订单数', value: orderCount, trend: t1.trend, trendUp: t1.trendUp },
      { title: '本月销售额', value: '¥' + sales.toLocaleString(), trend: t2.trend, trendUp: t2.trendUp },
      { title: '活跃用户', value: users, trend: t3.trend, trendUp: t3.trendUp },
      { title: '转化率', value: conversion, trend: t4.trend, trendUp: t4.trendUp }
    ]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 销售趋势（月销售额）
let salesCache = null;
let salesCacheTime = 0;
router.get('/overview/sales', async (req, res) => {
  try {
    const now = Date.now();
    if (salesCache && now - salesCacheTime < 60000) {
      return res.json(salesCache);
    }
    const nowDate = new Date();
    const start = new Date(nowDate.getFullYear(), nowDate.getMonth() - 6, 1);
    // 一次聚合统计近7个月
    const salesAgg = await orderModel.aggregate([
      { $match: { date: { $gte: start, $lte: nowDate } } },
      {
        $group: {
          _id: { $dateToString: { format: '%Y-%m', date: '$date' } },
          total: { $sum: '$amount' }
        }
      },
      { $sort: { _id: 1 } }
    ]);
    // 补全没有订单的月份
    const months = [];
    for (let i = 6; i >= 0; i--) {
      const d = new Date(nowDate.getFullYear(), nowDate.getMonth() - i, 1);
      const label = `${d.getMonth() + 1}月`;
      const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`;
      const found = salesAgg.find(item => item._id === key);
      months.push({ month: label, value: found ? found.total : 0 });
    }
    salesCache = months;
    salesCacheTime = now;
    res.json(months);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 用户增长
router.get('/overview/user-growth', async (req, res) => {
  try {
    // 近7个月
    const now = new Date();
    const months = [];
    for (let i = 6; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      months.push({
        label: `${d.getMonth() + 1}月`,
        start: new Date(d),
        end: new Date(d.getFullYear(), d.getMonth() + 1, 1)
      });
    }
    // 新增用户
    const newUsers = await Promise.all(months.map(async m => {
      return await usersModel.countDocuments({ createdAt: { $gte: m.start, $lt: m.end } });
    }));
    // 活跃用户
    const activeUsers = await Promise.all(months.map(async m => {
      return await usersModel.countDocuments({ lastLogin: { $gte: m.start, $lt: m.end } });
    }));
    res.json(months.map((m, i) => ({ month: m.label, newUsers: newUsers[i], activeUsers: activeUsers[i] })));
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 商品类别分布
const Canting = require('../../database/connacting');
let categoriesCache = null;
let categoriesCacheTime = 0;
router.get('/overview/categories', async (req, res) => {
  try {
    const now = Date.now();
    if (categoriesCache && now - categoriesCacheTime < 60000) {
      return res.json(categoriesCache);
    }
    // 按 category 分组统计数量
    const agg = await Canting.aggregate([
      { $group: { _id: "$category", count: { $sum: 1 } } }
    ]);
    const total = agg.reduce((sum, item) => sum + item.count, 0) || 1;
    const categories = agg.map(item => ({
      name: item._id || '未知',
      percentage: Math.round((item.count / total) * 100)
    }));
    categoriesCache = categories;
    categoriesCacheTime = now;
    res.json(categories);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// WebSocket 推送支持
let wsServer = null;
// 新增：记录上次推送的数据
let lastPayload = {};
// 新增：记录上一次业务数据和趋势
let lastStatsData = null;
let lastTrends = [null, null, null, null]
function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}
function setupWebSocket(server) {
  if (wsServer) return; // 防止重复注入
  const WebSocket = require('ws');
  wsServer = new WebSocket.Server({ server });

  function randInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  function randTrend() {
    const up = Math.random() > 0.5;
    const percent = (Math.random() * 10).toFixed(1) + '%';
    return { trend: (up ? '+' : '-') + percent, trendUp: up };
  }
  // 只在业务数据变化时才生成新 trend
  async function genStats() {
    // 真实统计
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
    const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 1);
    // 今日订单数
    const orderCount = await orderModel.countDocuments({ date: { $gte: today, $lt: tomorrow } });
    // 本月销售额
    const salesAgg = await orderModel.aggregate([
      { $match: { date: { $gte: monthStart, $lt: monthEnd } } },
      { $group: { _id: null, total: { $sum: "$amount" } } }
    ]);
    const sales = salesAgg[0]?.total || 0;
    // 活跃用户
    const users = await usersModel.countDocuments({ lastLogin: { $gte: today, $lt: tomorrow } });
    // 转化率（mock，除非有业务逻辑）
    const conversion = (Math.random() * 40).toFixed(1) + '%';
    const statsData = [orderCount, sales, users, conversion];
    // 只有业务数据变化时才生成新 trend
    if (!lastStatsData || statsData.some((v, i) => v !== lastStatsData[i])) {
      lastTrends = [0, 1, 2, 3].map(() => randTrend());
      lastStatsData = statsData;
    }
    return [
      { title: '今日订单数', value: orderCount, ...lastTrends[0] },
      { title: '本月销售额', value: '¥' + sales.toLocaleString(), ...lastTrends[1] },
      { title: '活跃用户', value: users, ...lastTrends[2] },
      { title: '转化率', value: conversion, ...lastTrends[3] }
    ];
  }
 
  function genTwins() {
    // 模拟订单流转各环节数量
    return [
      { id: 'order1', name: '待支付', count: randInt(20, 50), color: '#faad14' },
      { id: 'order2', name: '待发货', count: randInt(10, 30), color: '#1890ff' },
      { id: 'order3', name: '运输中', count: randInt(5, 20), color: '#52c41a' },
      { id: 'order4', name: '已签收', count: randInt(50, 100), color: '#13c2c2' },
      { id: 'order5', name: '退款中', count: randInt(0, 5), color: '#ff4d4f' }
    ];
  }

  function genWarehouse() {
    // 仓库分区和机器人
    return {
      areas: [
        { id: 'A', name: 'A区', stock: randInt(100, 300), x: 60, y: 60 },
        { id: 'B', name: 'B区', stock: randInt(50, 200), x: 180, y: 60 },
        { id: 'C', name: 'C区', stock: randInt(80, 250), x: 60, y: 160 },
        { id: 'D', name: 'D区', stock: randInt(30, 120), x: 180, y: 160 }
      ],
      robots: [
        { id: 'r1', name: '机器人1', x: randInt(60, 180), y: randInt(60, 160), status: Math.random() > 0.2 ? '空闲' : '作业' }
      ]
    };
  }

  function genLogistics() {
    // 车辆/包裹在地图上的位置
    return [
      { id: 'v1', type: '货车', x: randInt(20, 280), y: randInt(20, 120), status: '运输中', route: [[20, 20], [100, 60], [200, 100], [280, 120]] },
      { id: 'p1', type: '包裹', x: randInt(20, 280), y: randInt(20, 120), status: '派送中' }
    ];
  }

  wsServer.on('connection', async (client) => {
    // 连接时立即推送一次
    const stats = await genStats();
    const payload = {
      stats,
      monitor: {
        onlineUsers: randInt(200, 300),
        processingOrders: randInt(20, 60),
        avgResponse: (Math.random() * 2).toFixed(2) + 's',
        availability: (99 + Math.random()).toFixed(1) + '%'
      },
      twins: genTwins(),
      warehouse: genWarehouse(),
      logistics: genLogistics()
    };
    client.send(JSON.stringify(payload));
  });

  setInterval(async () => {
    // 生成新数据
    const stats = await genStats();
    const payload = {
      stats,
      monitor: {
        onlineUsers: randInt(200, 300),
        processingOrders: randInt(20, 60),
        avgResponse: (Math.random() * 2).toFixed(2) + 's',
        availability: (99 + Math.random()).toFixed(1) + '%'
      },
      twins: genTwins(),
      warehouse: genWarehouse(),
      logistics: genLogistics()
    };
    // 只有数据有变化才推送
    if (!deepEqual(payload, lastPayload)) {
      wsServer.clients.forEach(client => {
        if (client.readyState === (wsServer.WebSocket ? wsServer.WebSocket.OPEN : 1)) {
          client.send(JSON.stringify(payload));
        }
      });
      lastPayload = payload;
    }
  }, 5000);
}

// 业务事件模拟：新订单和用户登录时推送最新 stats
async function pushStatsToClients() {
  const stats = await genStats();
  const payload = {
    stats
  };
  if (wsServer) {
    wsServer.clients.forEach(client => {
      if (client.readyState === (wsServer.WebSocket ? wsServer.WebSocket.OPEN : 1)) {
        client.send(JSON.stringify(payload));
      }
    });
  }
}

// 新订单事件模拟
router.post('/mock-order', (req, res) => {
  // 这里应有真实订单写入逻辑
  pushStatsToClients();
  res.json({ code: 200, message: '新订单已推送大屏' });
});

// 用户登录事件模拟
router.post('/mock-login', (req, res) => {
  // 这里应有真实登录逻辑
  pushStatsToClients();
  res.json({ code: 200, message: '用户登录已推送大屏' });
});

module.exports = router;
module.exports.setupWebSocket = setupWebSocket;